package noblob;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import model.Movie;
import model.PMF;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

@SuppressWarnings("serial")
public class ProvaUploadNOblobServlet extends HttpServlet {
	
//	static byte[] img;
	
	public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {
	try {
	ServletFileUpload upload = new ServletFileUpload();
//	upload.setSizeMax(50000); //5Kb
//	res.setContentType("text/plain");
	PrintWriter out = res.getWriter();

	try {
	FileItemIterator iterator = upload.getItemIterator(req);
	while (iterator.hasNext()) {
	FileItemStream item = iterator.next();
	InputStream in = item.openStream();

	if (item.isFormField()) {
	out.println("Got a form field: " + item.getFieldName());
	} else {
	Movie img= new Movie();	
	img.setTitle(item.getName());
	img.setImageType(item.getContentType());
	try {
	img.setImage(IOUtils.toByteArray(in));
	} finally {
		 IOUtils.closeQuietly(in);
	}
	
	//MEMORIZZIAMO L'IMG NEL DATASTORE USANDO PMF
	PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
        // Store the image in App Engine's datastore
    	
        pm.makePersistent(img);
    } finally {
        pm.close();
    }
	
    res.sendRedirect("/image.jsp?title="+img.getTitle());
	
//		try {
//			 img= IOUtils.toByteArray(in);
//			} finally {
//			 IOUtils.closeQuietly(in);
//			}

		
	}
	}
	} catch (SizeLimitExceededException e) {
	out.println("You exceeded the maximu size ("
	+ e.getPermittedSize() + ") of the file ("
	+ e.getActualSize() + ")");
	}
	} catch (Exception ex) {

	throw new ServletException(ex);
	}
	
	
	
	}

}
